import { escape, map } from 'lodash-es';
export function keysToString(value: string[] | string): string {
  let v = value;
  if (!(v instanceof Array)) {
    v = [v];
  }
  v = map(v, (v) => escape(v.replace(/(^\(|\)$)/g, '')));
  return v.join(', ');
}

export function sortKeys(
  sort: string[],
  presort: string[] | undefined,
): string {
  return map(sort, (v) => {
    let result = escape(v);
    if (presort) {
      result +=
        presort.indexOf(v) !== -1
          ? '&nbsp;<span class="text-muted">(presort)</span>'
          : '';
    }
    return result;
  }).join(', ');
}

export function formatNumber(n: number) {
  if (!n) {
    return 0;
  }
  const parts = n.toString().split('.');
  const integerPart = parts[0];
  let decimalPart = parts[1] || '';

  const formattedIntegerPart = integerPart.replace(
    /\B(?=(\d{3})+(?!\d))/g,
    ',',
  );

  if (decimalPart.length > 3) {
    decimalPart = parseFloat('0.' + decimalPart)
      .toFixed(2)
      .slice(2);
  }

  if (decimalPart) {
    return formattedIntegerPart + '.' + decimalPart;
  } else {
    return formattedIntegerPart;
  }
}
